import os
import logging
import clients
import textwrap

from clients.mastodon import MastodonBot
from persist import JsonObject
from telegram.ext import Updater, MessageHandler, CommandHandler, Filters
from webpreview import web_preview

class TelegramBot(object):

    def __init__(self, token):
        self.chats = {}
        self.updater = Updater(token, use_context = True)
        self.updater.dispatcher.add_handler(MessageHandler(Filters.status_update, self._status))
        self.updater.dispatcher.add_handler(MessageHandler(Filters.entity('url'), self._url))

        for c in 'start stop help post code status'.split():
            self.updater.dispatcher.add_handler(CommandHandler(c, getattr(self, '_' + c)))

    def _start(self, update, context):
        m = update.message
        m.reply_text(textwrap.dedent('''
            Hello. I will send the links on this chat to mastodon.
            Send /help for more information.
            ''').strip())
        mastodon = self._get_mastodon(m.chat.id)
        url = mastodon.get_oauth_url()
        text = ('[Please click here to go to mastodon](' + url +'),' +
            ' then copy the code from mastodon page' +
            ' and paste it here as `/code <CODE>`')
        if not mastodon.is_logged_in:
            update.message.reply_markdown(text)

    # TODO generate help from pydoc
    def _help(self, update, context):
        text = textwrap.dedent('''
        This bot sends all links message in this chat to mastodon.

        Commands:
        /start      : Show the welcome message.
        /code       : Link to a mastodon account.
        /status     : Check bot status.
        /help       : This message.
        /stop       : Stop sending links to mastodon.
        ''').strip()
        update.message.reply_text(text)

    def _post(self, update, context):
        if not self.chats.data:
            self.chats.load()

        m = update.message
        params = m.text.split()
        if len(params) < 2:
            subreddit = self.chats[update.message.chat.id]
            if subreddit:
                text = 'This bot is sending links to /r/' + subreddit
            else:
                text = 'This bot was not configured yet.'
            text += textwrap.dedent('''

            Please inform the subreddit alongside the command to send the links
            posted on this chat to {} subreddit.
            e.g: /post pics
            '''.format('another' if subreddit else 'a'))
            m.reply_text(text)
            return

        subreddit = params[1]
        if not self.reddit.exists(subreddit):
            m.reply_text('The subreddit "{}" doesn\'t exist!'.format(subreddit))
            return

        self.chats[m.chat.id] = subreddit
        self.chats.save()
        m.reply_text('All links from "{}" will be posted to {}'.format(
                        m.chat.title or m.chat.username, subreddit))


    def _url(self, update, context):
        m = update.message
        url = m.text
        title, description, image = web_preview(url, parser='html.parser')
        mastodon = self._get_mastodon(m.chat.id)
        mastodon.submit(title, url)

    def _stop(self, update, context):
        m = update.message
        m.reply_text('This bot will no longer post links to mastodon.')
        del self.chats[m.chat.id]
        self.chats.save()

    def _status(self, update, context):
        m = update.message
        if hasattr(m, 'new_chat_member') and m.new_chat_member.id == bot.id:
                self._start(bot, update)
        if hasattr(m, 'left_chat_member') and m.new_chat_member.id == bot.id:
                self._finish(bot, update)

    def _code(self, update, context):
        m = update.message
        params = m.text.split()
        mastodon = self._get_mastodon(m.chat.id)
        mastodon.login(m.chat.id, params[1])
        self._status(update, context)

    def _status(self, update, context):
        m = update.message
        params = m.text.split()
        mastodon = self._get_mastodon(m.chat.id)
        if mastodon.is_logged_in:
            update.message.reply_markdown('Mastodon succesfully logged in')
        else:
            update.message.reply_markdown('Mastodon failed to log in')

    def _get_mastodon(self, chat_id):
        return self.chats.get(chat_id, MastodonBot(chat_id))

    def run(self):
        self.updater.start_polling()
        self.updater.idle()
